<?php
class JBSRoles {
	/*
	 * Check if the user has right to access the function
	 * */
	public static function checkFunction($user, $function) {
		$db = & JFactory :: getDBO();
		$query = "SELECT " .
				"	f.name AS function_name, " .
				"	u.system_user_id AS user_id, " .
				"	su.username AS username " .
				"FROM " .
				"	#__jbschedule_functions f " .
				"	Inner Join #__jbschedule_roles_functions rf ON f.id = rf.function_id " .
				"	Inner Join #__jbschedule_users u ON u.tsb_role_id = rf.role_id " .
				"	Inner Join #__users su ON u.system_user_id = su.id " .
				"WHERE " .
				"	u.system_user_id = '". $user->id ."' AND f.name = '".$function."'";

		$db->setQuery($query);
		$result = $db->loadResult();
		return $result != null;
	}

	/*
	 * Check access permission to a function of current login user
	 *
	 * This function should be used in Controller layer of MVC pattern
	 * */
	public static function checkPermission($controller, $function, $redirectUrl, $message = null, $redirect = true){
		//Super Administrator always have full access
		if (JBSRoles::isSuperAdmin()){
			return true;
		}

		//If no permission
		if (!JBSRoles::checkFunction(JFactory :: getUser(), $function)) {
			if($message == null)
				$msg = JText :: _('_CAL_LANG_NOPERMISSION');
			else
				$msg = JText :: _($message);

			//Redirect the page
			if($redirect){
				$redirectURL = empty($redirectURL) ? 'index.php?option=com_jbschedule' : $redirectURL;
				$controller->setRedirect($redirectURL, $msg);
			}

			return false;
		}
		return true;
	}

	/*
	 * Check if loged in user is Super Administrtor or not
	 * */
	 public static function isSuperAdmin(){
		$user = & JFactory::getUser();
		return ($user->get('usertype') == 'Super Administrator');
	 }
}

/*
 * Utilities class
 *
 * */

class Utils{
	/*
	  * Load settings from Database
	  * */
	 public static function loadSetting(){
	 	$db =& JFactory::getDBO();
		$query = ' SELECT * FROM #__jbschedule_settings LIMIT 1';
		$db->setQuery( $query );
		$settings = $db->loadObject();
		if (!$settings) {
			$settings = new stdClass();
			$settings->id = 0;
			$settings->send_notify_email = false;
			$settings->sender_address = null;
			$settings->week_start_on = '0';
			$settings->default_calendar_page = 'month';
			$settings->time_format = '12h';
			$settings->theme = 'blue';
		}
		return $settings;
	 }

	/*
	 * Return current settings
	 * */
	 public static function getSettings(){
	 	//Check the session first
	 	$session = &JSession::getInstance(null, null);
		$settings = $session->get('settings');
		//If there is no settings object in session
		if($settings == null){
			$settings = Utils::loadSetting();	//Load settings from Database
			$session->set('settings', $settings);	//Put retrived settings into session
		}

		return $settings;
	 }
}
?>